﻿
using System;
using System.Net.Mail;
using NTQOnlineExam.Services.CommandService.Content;
using NTQOnlineExam.Services.CommandService.Email;
using NTQOnlineExam.Services.Infrastructure.Utility;

namespace NTQOnlineExam.Services.CommandService
{
    public class ContentCommandService : IContentCommandService
    {
        private readonly IEmailService _emailService;

        public ContentCommandService(IEmailService emailService)
        {
            _emailService = emailService;
        }

        public void SendContactEmail(SendContactCommand command)
        {
            Guard.ArgumentIsNotNull(command, "command");
            Guard.ArgumentIsNotNull(command.Email, "email");
            Guard.ArgumentIsNotNull(command.Name, "name");
            Guard.ArgumentIsNotNull(command.Message, "message");
            Guard.ArgumentIsNotNull(command.Recipient, "recipient");
            var email = BuildContactEmail(command.Recipient, command.BccRecipient, command.Name, command.Email, command.Message);
            _emailService.SendEmail(email);
        }

        private MailMessage BuildContactEmail(string recipient, string bcc, string name, string emailAddress, string message)
        {
            var mailBody = TranslateMergeField(Resources.Content.ContactBody, name, emailAddress, message);
            var mailSubject = TranslateMergeField(Resources.Content.ContactHeader, name, emailAddress, message);

            var email = new MailMessage();
            email.To.Add(new MailAddress(recipient));
            if (!string.IsNullOrWhiteSpace(bcc))
            {
                email.Bcc.Add(bcc);
            }
            email.Subject = mailSubject;
            email.Body = mailBody;
            email.IsBodyHtml = true;
            return email;
        }


        private string TranslateMergeField(string body, string name, string email, string message)
        {
            var result = body.Replace("{Contact_Email}", email).Replace("{Contact_Name}", name).Replace("{Contact_Message}", message);
            return result;
        }
    }
}
